package com.tzxs.pay.main.gather;

import android.app.Activity;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.PopupWindowCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.tzxs.pay.R;
import com.tzxs.pay.BR;
import com.tzxs.pay.databinding.ActivityAutListBinding;
import com.tzxs.pay.databinding.ItemBillAuthorizationBinding;
import com.tzxs.pay.databinding.TitlePopBinding;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.bill.detail.AutTncActivity;
import com.tzxs.pay.main.bill.detail.AutTradedDetailActivity;
import com.tzxs.pay.main.bill.model.AutBillImp;
import com.tzxs.pay.main.bill.model.AutOrderBean;
import com.tzxs.pay.main.bill.viewmodel.BillViewModel;
import com.tzxs.pay.util.IAdapter;
import com.tzxs.pay.util.IHolder;
import com.tzxs.pay.util.StatusBarColorSetter;
import com.tzxs.pay.util.viewmodel.Callback;

import java.util.List;

/**
 * 预授权订单列表
 */
public class AutListActivity extends BaseActivity<ActivityAutListBinding> implements IAdapter.ItemNavigator<AutBillImp> {
    private static final String TAG = AutListActivity.class.getSimpleName();
    //选择条件是否显示
    private boolean isShow = false;
    //预授权列表类型
    private int type = 0;//
    //pop
    private PopupWindow popupWindow;//pop
    private BillViewModel model;
    private int page = 1;//默认第一页

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_aut_list;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, Color.parseColor("#FAFAFA"));
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        dataBinding.autListRec.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.autListToolbar.setTitle("");
        setSupportActionBar(dataBinding.autListToolbar);
        //绑定viewModel
        dataBinding.setViewModel(model);
        dataBinding.autListToolbar.setNavigationOnClickListener(v -> onBackPressed());
        dataBinding.autListToolbar.setOnMenuItemClickListener(item -> {
            if (item.getItemId() == R.id.toolbar_menu_search) {
                Intent intent = new Intent(AutListActivity.this, SearchAutActivity.class);
                startActivity(intent);
            }
            return false;
        });
        dataBinding.autListTitle.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
        //默认为预授权账单

        dataBinding.autListTitle.setText("预授权账单");
        //设置drawable
        dataBinding.autListTitle.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0,
                R.drawable.aut_close, 0);
        //显示pop
        dataBinding.setListener(() -> {
            Log.d(TAG, "showPop: 进入点击事件");
            initPop();
            isShow = true;
            dataBinding.autListTitle.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0,
                    R.drawable.ic_triangle_close, 0);
        });


        getData(0);//进入后第一次获取数据


        //刷新
        dataBinding.refresh.setOnRefreshListener(refreshLayout -> {
            page = 1;
            //获取数据
            model.getDepositBills(false, null, page, 10, "", "", null,
                    null, type, null, () -> refreshLayout.finishRefresh(2000));

        });
        //加载更多
        dataBinding.refresh.setOnLoadMoreListener(refreshLayout -> {
            ++page;
            model.getDepositBills(false, null, page, 10, "", "", null,
                    null, type, null, new Callback() {
                        @Override
                        public void success() {
                            refreshLayout.finishLoadMore(2000);
                        }
                    });


        });

        //设置适配器
        setDataAdapter();
    }

    private void getData(int payStatus) {
        //获取数据
        model.getDepositBills(false, null, page, 10, "", "", null,
                null, payStatus, null, new Callback() {
                    @Override
                    public void success() {
                        Log.d(TAG, "success: 获取数据成功！");
                    }
                });

    }


    //设置适配器
    private void setDataAdapter() {
        //设置适配器
        dataBinding.autListRec.setAdapter(new IAdapter<AutBillImp, ViewDataBinding>() {
            @Override
            protected int getLayoutId(int viewType) {

                return R.layout.item_bill_authorization;
            }

            @Override
            protected int getDataBRId(int itemViewType) {

                return BR.order_aut;
            }

            //判断两个item的订单号是否相等
            @Override
            public boolean areItemsTheSame(List<AutBillImp> oldData, List<AutBillImp> data, int oldItemPosition, int newItemPosition) {
                if (oldData.get(oldItemPosition) instanceof AutOrderBean.DataBean && data.get(newItemPosition) instanceof AutOrderBean.DataBean) {
                    return ((AutOrderBean.DataBean) oldData.get(oldItemPosition)).getOut_order_no().equals(((AutOrderBean.DataBean) data.get(newItemPosition)).getOut_order_no());
                }
                return super.areItemsTheSame(oldData, data, oldItemPosition, newItemPosition);
            }

            @Override
            public boolean areContentsTheSame(List<AutBillImp> oldData, List<AutBillImp> data, int oldItemPosition, int newItemPosition) {
                if (oldData.get(oldItemPosition) instanceof AutOrderBean.DataBean && data.get(newItemPosition) instanceof AutOrderBean.DataBean) {
                    return ((AutOrderBean.DataBean) oldData.get(oldItemPosition)).getPay_status() == (((AutOrderBean.DataBean) data.get(newItemPosition)).getPay_status());
                } else {
                    return true;
                }

            }

            @Override
            protected void convert(@NonNull ViewDataBinding binding, int position, AutBillImp autBillImp) {
                super.convert(binding, position, autBillImp);
                if (binding instanceof ItemBillAuthorizationBinding) {
                    ItemBillAuthorizationBinding dataBinding = (ItemBillAuthorizationBinding) binding;
                    dataBinding.setItemNavigator(AutListActivity.this);
                }
            }

            @Override
            public void onBindViewHolder(IHolder<ViewDataBinding> holder, int position) {
                super.onBindViewHolder(holder, position);
                if (holder.binding instanceof ItemBillAuthorizationBinding) {
                    ItemBillAuthorizationBinding dataBinding = (ItemBillAuthorizationBinding) holder.binding;
                    AutOrderBean.DataBean bean = (AutOrderBean.DataBean) getData().get(position);
                    String payStr = null;
                    //订单状态
                    switch (bean.getPay_status()) {
                        case 1:
                            payStr = "等待结算";
                            dataBinding.autState.setTextColor(Color.parseColor("#1F78CF"));
                            break;
                        case 2:
                            payStr = "支付失败";
                            dataBinding.autState.setTextColor(Color.parseColor("#999999"));
                            break;
                        case 3:
                            payStr = "等待支付";
                            dataBinding.autState.setTextColor(Color.parseColor("#27AA30"));
                            break;
                        case 4:
                            payStr = "结算成功";
                            dataBinding.autState.setTextColor(Color.parseColor("#ED433F"));
                            break;
                        case 5:
                            payStr = "已退款";
                            dataBinding.autState.setTextColor(Color.parseColor("#EB9205"));
                            break;

                    }

                    dataBinding.autState.setText(payStr);

                    //支付方式
                    switch (bean.getPay_type()) {
                        case "weixin":
                            dataBinding.autPayIcon.setImageResource(R.drawable.ic_wechat);
                            break;
                        case "alipay":
                            dataBinding.autPayIcon.setImageResource(R.drawable.ic_alipay);
                            break;
                        default:
                            dataBinding.autPayIcon.setImageResource(R.drawable.ic_unionpay);
                            break;
                    }
                }


            }
        });
    }

    //初始化pop
    private void initPop() {
        if (popupWindow == null) {
            popupWindow = new PopupWindow(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            //获取view
            final TitlePopBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.title_pop, null, false);
            popupWindow.setContentView(binding.getRoot());
            binding.setListener(view -> {
                clearStatus(binding);
                dataBinding.autListTitle.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0,
                        R.drawable.aut_close, 0);

                switch (view.getId()) {
                    case R.id.pop_aut_list:

                        binding.popAutList.setSelected(true);
                        dataBinding.autListTitle.setText("预授权账单");
                        Log.d(TAG, "onClick: 预授权账单");
                        type = 0;
                        break;
                    case R.id.pop_settlement_list:

                        Log.d(TAG, "onClick: 可结算账单");
                        binding.popSettlementList.setSelected(true);
                        dataBinding.autListTitle.setText("可结算账单");
                        type = 1;
                        break;

                    case R.id.pop_overdue_list:

                        binding.popOverdueList.setSelected(true);
                        Log.d(TAG, "onClick: 即将过期账单");
                        dataBinding.autListTitle.setText("即将过期账单");
                        type = 1;

                        break;
                    case R.id.pop_settlemented_list:

                        binding.popSettlementedList.setSelected(true);
                        Log.d(TAG, "onClick: 已结算账单");
                        dataBinding.autListTitle.setText("已结算账单");
                        type = 4;
                        break;
                    case R.id.pop_refund_list:

                        binding.popRefundList.setSelected(true);
                        Log.d(TAG, "onClick: 已退款账单");
                        dataBinding.autListTitle.setText("已退款账单");
                        type = 5;
                        break;
                    case R.id.pop_fail_list:

                        binding.popFailList.setSelected(true);
                        Log.d(TAG, "onClick: 支付失败订单");
                        dataBinding.autListTitle.setText("支付失败订单");
                        type = 2;
                        break;
                }
                popupWindow.dismiss();

                isShow = false;
            });


        }


        if (popupWindow != null) {
            popupWindow.setOnDismissListener(() -> {
                //进入页面获取数据
                Log.d(TAG, "onCreate: pop消失 重新获取数据 ");
                getData(type);
            });
        }
        PopupWindowCompat.showAsDropDown(popupWindow, dataBinding.autListToolbar, 0, 0, Gravity.CENTER);


    }

    /**
     * 清除控件选中状态
     *
     * @param binding binding
     */
    private void clearStatus(TitlePopBinding binding) {

        binding.popAutList.setSelected(false);
        binding.popSettlementList.setSelected(false);
        binding.popOverdueList.setSelected(false);
        binding.popSettlementedList.setSelected(false);
        binding.popRefundList.setSelected(false);
        binding.popFailList.setSelected(false);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search, menu);
        return true;
    }


    //
    @Override
    public void itemClick(AutBillImp item) {
        if (item instanceof AutOrderBean.DataBean) {
            AutOrderBean.DataBean dataBean = (AutOrderBean.DataBean) item;
            Intent intent;
            if (dataBean.getPay_status() == 1) {//订单未结算的情况下跳转
                intent = new Intent(this, AutTncActivity.class);

            } else {
                intent = new Intent(this, AutTradedDetailActivity.class);
            }
            intent.putExtra("orderId", dataBean.getOut_order_no());
            startActivity(intent);
        }
    }
}
